package com.HandleExceptioin;


import com.Common.Consts;
import org.apache.tomcat.util.bcel.Const;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class GlobalHandleException {
    private static Logger log = LoggerFactory.getLogger(GlobalHandleException.class);

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Map<String, Object> errorHandler(HttpServletRequest request, Exception e) {
        String actionUrl = request.getRequestURL().toString();
        String urlPara = request.getQueryString();
        Enumeration<String> names = request.getParameterNames();
        StringBuilder paraVal = new StringBuilder();
        while (names.hasMoreElements()) {
            String paName = (String) names.nextElement();
            paraVal.append(paName);
            paraVal.append("=");
            String[] paVals = request.getParameterValues(paName);
            if (paVals != null) {
                for (int index = 0; index < paVals.length; index++) {
                    paraVal.append(paVals[index]);
                    paraVal.append(",");
                }
            }
        }
        //request.getContextPath().
        log.error("------begin-------{}", new Date());
        log.error("actionUrl:{}", actionUrl);
        log.error("params:{}", paraVal);
        log.error("urlPara:{}", urlPara);
        log.error("error:{}", e.getMessage());
        log.error("error:{0}", e);
        log.error("------end-------");
        Map<String, Object> ret = new HashMap<>(12);
        ret.put(Consts.Status, ExceptionEnum.FAIL.getCode());
        ret.put(Consts.MSG, ExceptionEnum.FAIL.getMessage());

        return ret;
    }
}
